<template>
  <div class="document-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文档编辑器</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="saveDocument">保存</el-button>
        <el-button style="float: right; padding: 3px 0; margin-right: 10px" type="text" @click="downloadDocument">下载</el-button>
      </div>
      
      <!-- TinyMCE编辑器 -->
      <div class="editor-container">
        <editor v-model="content" :init="editorInit" @onInit="handleEditorInit" />
      </div>
    </el-card>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce';
import Editor from '@tinymce/tinymce-vue';
import { getContent, saveContent } from "@/api/system/document";

export default {
  components: {
    Editor
  },
  data() {
    return {
      content: '',
      editorInit: {
        height: 500,
        menubar: false,
        plugins: [
          'advlist autolink lists link image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount'
        ],
        toolbar: 'undo redo | formatselect | ' +
          'bold italic backcolor | alignleft aligncenter ' +
          'alignright alignjustify | bullist numlist outdent indent | ' +
          'removeformat | help',
        content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
      },
      documentId: null,
      fileName: ''
    }
  },
  created() {
    this.documentId = this.$route.query.id;
const queryParams = Object.keys(this.$route.query);
console.log(queryParams); // 输出类似 ["id", "name"]
    this.fileName = this.$route.query.fileName;
    if (this.documentId) {
      this.loadDocument();
    }
  },
  methods: {
    // 加载文档内容
    loadDocument() {
      getContent({ filePath: this.documentId }).then(response => {
        if (response.code === 200) {
          this.content = response.data;
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    
    // 保存文档
    saveDocument() {
      saveContent({ 
        filePath: this.documentId,
        content: this.content 
      }).then(response => {
        if (response.code === 200) {
          this.$message.success("保存成功");
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    
    // 下载文档
    downloadDocument() {
      window.open(process.env.VUE_APP_BASE_API + "/system/document/download?filePath=" + encodeURIComponent(this.documentId));
    },
    
    // 编辑器初始化回调
    handleEditorInit(editor) {
      console.log('Editor initialized:', editor);
    }
  }
}
</script>

<style scoped>
.document-container {
  padding: 20px;
}

.editor-container {
  margin-top: 20px;
}
</style>